package com.ffapp.demo.basis;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ffapp.demo.R;
import com.ffapp.demo.bean.LoginBean;
import com.ffapp.demo.chat.ChatGroupActivity;
import com.ffapp.demo.util.MyUtils;
import com.lzf.easyfloat.EasyFloat;
import com.lzf.easyfloat.enums.ShowPattern;
import com.lzf.easyfloat.enums.SidePattern;
import com.lzf.easyfloat.interfaces.OnInvokeView;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import my.LogUtil;
import my.SystemParamsUtils;
import my.ViewUtils;
import my.base.BaseActivity;


public class BasisActivity extends BaseActivity {

    private String TAG = BasisActivity.class.getName();

    protected BasisActivity mContext;

    public static boolean isActive = true;

    QMUITipDialog mLoadingDialog;

    boolean isDefautTrans = true; //是否设置状态栏透明

    private boolean isNeedSign = true;

    @Override
    public void initViews() {
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        initDataS();
    }

    public void setDefautTrans(boolean isDefautTrans) {
        this.isDefautTrans = isDefautTrans;
    }

    @Override
    public void setContentView(int layoutResID) {
        // TODO Auto-generated method stub
        super.setContentView(layoutResID);
        setHideInputZone(R.id.main_view);
        setHideInputZone(R.id.main_view2);
        setTitleStatusZone();
//		QMUIStatusBarHelper.translucent(mContext);
//		mLoadingDialog = new QMUITipDialog.Builder(mContext)
//				.setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
//				.setTipWord("正在加载")
//				.create();
    }


    @Override
    public void setContentView(View view) {
        super.setContentView(view);

    }

    @Override
    public void initConfig(Bundle savedInstanceState) {
        overridePendingTransition(R.anim.left_in, R.anim.left_out);
        super.initConfig(savedInstanceState);
        mContext = this;
        initDataS();
    }

    @Override
    public void finish() {
        ViewUtils.hideInput(mContext);
        // TODO Auto-generated method stub
        super.finish();
        // BasisApp.actityList.remove(this);
        overridePendingTransition(R.anim.right_in, R.anim.right_out);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
//		MyHttpUtils.getAsyncHttpClient().cancelAllRequests(true);
        super.onDestroy();
//		if (mImmersionBar != null)
//			mImmersionBar.destroy();  //必须调用该方法，防止内存泄漏，不调用该方法，如果界面bar发生改变，在不关闭app的情况下，退出此界面再进入将记忆最后一次bar改变的状态

    }

    private void initDataS() {
//		mLoadingDialog = new LoadingDialog(mContext);

        if(LoginBean.isLogin() && LoginBean.getInstance().getUserInfo().isUserCompany() && isNeedSign){
            EasyFloat.with(this)
                    // 设置浮窗xml布局文件，并可设置详细信息
                    .setLayout(R.layout.user_float_view, new OnInvokeView() {
                        @Override
                        public void invoke(View view) {
                            ((TextView)view.findViewById(R.id.float_text_name)).setText(LoginBean.getInstance().getUserInfo().getName() + MyUtils.getPhoneLastFour(mContext));

//                            ((TextView)view.findViewById(R.id.float_text_mobile)).setText(new MySharedPreferences(mContext).getUser());
                        }
                    })
            // 设置浮窗显示类型，默认只在当前Activity显示，可选一直显示、仅前台显示、仅后台显示
                 .setShowPattern(ShowPattern.CURRENT_ACTIVITY)
                    // 设置吸附方式，共15种模式，详情参考SidePattern
                    .setSidePattern(SidePattern.DEFAULT)
                    // 设置浮窗的标签，用于区分多个浮窗
                    .setTag("float")
                    // 设置浮窗是否可拖拽，默认可拖拽
                    .setDragEnable(false)
                    // 系统浮窗是否包含EditText，仅针对系统浮窗，默认不包含
                    .hasEditText(false)
                    // 设置浮窗固定坐标，ps：设置固定坐标，Gravity属性和offset属性将无效
//                    .setLocation(100, 200)
                    // 设置浮窗的对齐方式和坐标偏移量
                    .setGravity(Gravity.BOTTOM | Gravity.RIGHT, -30, -50)
                    // 设置宽高是否充满父布局，直接在xml设置match_parent属性无效
                    .setMatchParent(false, false)
                    // 设置Activity浮窗的出入动画，可自定义，实现相应接口即可（策略模式），无需动画直接设置为null
                    .setAnimator(null)
                    // 设置系统浮窗的出入动画，使用同上
                    .setAppFloatAnimator(null)
                    // 设置系统浮窗的不需要显示的页面
                    .setFilter(ChatGroupActivity.class)

    .show();
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        JAnalyticsInterface.onPageStart(getApplicationContext(), this.getClass().getCanonicalName());
        if (!isActive) {
            // app 从后台唤醒，进入前台
            LogUtil.i(TAG, this.getClass().getName() + "---->从后台唤醒进入前台");
            isActive = true;
//			IntentUtils.sendBrocastAction(mContext, HomeActivity.ACTION_CHANGEINBACKGROUND);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
//        JAnalyticsInterface.onPageEnd(getApplicationContext(), this.getClass().getCanonicalName());
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
//		LogUtil.i(this.getClass().getName() + "------>onStop");
        if (!SystemParamsUtils.isAppOnForeground(mContext)) {
            // app 进入后台
            LogUtil.i(TAG, this.getClass().getName() + "---->进入后台");
            isActive = false;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(),0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        //必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v,MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {//点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }



    public void setTitle(String titleStr) {
        TextView title = findViewById(R.id.base_title_text);
        if (title == null) {
            super.setTitle(titleStr);
            return;
        }
        title.setVisibility(View.VISIBLE);
        title.setText(titleStr);
        findViewById(R.id.base_title_logo).setVisibility(View.GONE);
    }

    public void setTitle(int titleResId) {
        String titleStr = getResources().getString(titleResId);
        setTitle(titleStr + "");
    }

    public void setTitleStatusZone(){
        if(isDefautTrans){
            QMUIStatusBarHelper.translucent(mContext);
            QMUIStatusBarHelper.setStatusBarLightMode(mContext);
            if (findViewById(R.id.base_title_root) == null)
                return;
            setTitleBg(R.drawable.top_bar_bg);
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) findViewById(R.id.base_title_view).getLayoutParams();
            layoutParams.topMargin = QMUIStatusBarHelper.getStatusbarHeight(mContext);
            findViewById(R.id.base_title_view).setLayoutParams(layoutParams);
        }else {
//            QMUIStatusBarHelper.
            QMUIStatusBarHelper.setStatusBarLightMode(mContext);
        }

    }

    public void setTitleBg(int resId) {
        if (isDefautTrans) {
            if (findViewById(R.id.base_title_root) == null)
                return;
            findViewById(R.id.base_title_root).setBackgroundResource(resId);
            findViewById(R.id.base_title_view).setBackgroundResource(R.color.transparent);
        } else {
            if (findViewById(R.id.base_title_view) == null)
                return;
            findViewById(R.id.base_title_view).setBackgroundResource(resId);
        }

    }

    public void setTitleRightButton(int drawableRes,
                                    OnClickListener onClickListener) {
        if (findViewById(R.id.base_btn_right) == null)
            return;
        findViewById(R.id.base_btn_right).setOnClickListener(onClickListener);
        ((ImageView) findViewById(R.id.base_btn_right_icon))
                .setImageResource(drawableRes);
        findViewById(R.id.base_btn_right).setVisibility(
                drawableRes == 0 ? View.INVISIBLE : View.VISIBLE);
    }

    public void setTitleRightButton2(int drawableRes,
                                     OnClickListener onClickListener) {
        if (findViewById(R.id.base_btn_right2) == null)
            return;
        findViewById(R.id.base_btn_right2).setOnClickListener(onClickListener);
        ((ImageView) findViewById(R.id.base_btn_right_icon2))
                .setImageResource(drawableRes);
        findViewById(R.id.base_btn_right2).setVisibility( drawableRes == 0 ? View.INVISIBLE : View.VISIBLE);
    }

    public void setTitleRightButton3(int drawableRes,
                                     OnClickListener onClickListener) {
        if (findViewById(R.id.base_btn_right3) == null)
            return;
        findViewById(R.id.base_btn_right3).setOnClickListener(onClickListener);
        ((ImageView) findViewById(R.id.base_btn_right_icon3))
                .setImageResource(drawableRes);
        findViewById(R.id.base_btn_right3).setVisibility( drawableRes == 0 ? View.INVISIBLE : View.VISIBLE);
    }


    public void setTitleLeftButton(int drawableRes,
                                   OnClickListener onClickListener) {
        if (findViewById(R.id.base_btn_back) == null)
            return;
        findViewById(R.id.base_btn_back).setOnClickListener(onClickListener);
        ((ImageView) findViewById(R.id.base_btn_back_icon))
                .setImageResource(drawableRes);
        findViewById(R.id.base_btn_back).setVisibility(View.VISIBLE);
    }

    public void setTitleLeftButton(OnClickListener onClickListener) {
        if (findViewById(R.id.base_btn_back) == null)
            return;
        if (onClickListener == null) {
            onClickListener = new OnClickListener() {
                public void onClick(View v) {
                    ViewUtils.hideInput(mContext);
                    finish();
                }
            };
        }
        findViewById(R.id.base_btn_back).setOnClickListener(onClickListener);
        findViewById(R.id.base_btn_back).setVisibility(View.VISIBLE);
    }

    public void setTitleRightText(String text, OnClickListener listenner) {
        TextView textRight = findViewById(R.id.base_title_right_text);
        if (textRight == null)
            return;
        textRight.setVisibility(View.VISIBLE);
        textRight.setText(text);
        textRight.setOnClickListener(listenner);
    }

    public void setTitleRightText(int titleResId, OnClickListener listenner) {
        String titleStr = getResources().getString(titleResId);
        setTitleRightText(titleStr + "", listenner);
    }

    public void setTitleLeftText(String text, OnClickListener listenner) {
        TextView textRight = findViewById(R.id.base_title_left_text);
        if (textRight == null)
            return;
        textRight.setVisibility(View.VISIBLE);
        textRight.setText(text);
        textRight.setOnClickListener(listenner);
    }

    public void setTitleLeftText(int titleResId, OnClickListener listenner) {
        String titleStr = getResources().getString(titleResId);
        setTitleLeftText(titleStr + "", listenner);
    }


    public void showToast(String content) {
        try {
            BasisApp.showToast(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showToast(int resId) {
        try {
            BasisApp.showToast(resId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String getIntentString(String key, String def) {
        String result = getIntent().getStringExtra(key);
        if (TextUtils.isEmpty(result))
            result = def;
        return result;
    }

    public void setHideInputZone(int resId) {
        if (findViewById(resId) != null) {
            findViewById(resId).setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // TODO Auto-generated method stub
                    ViewUtils.hideInput(mContext, v);
                    return false;
                }
            });
        }
    }

    public void showProgress() {
        showLoadingDialog();
    }

    public void showLoading() {
        showLoadingDialog();
    }

    public void hideLoading() {
        hideLoadingDialog();
    }

    public void dismissProgress() {
        hideLoadingDialog();
    }

    public void showLoadingDialog() {
        if (isFinishing()) return;
        checkDialog(mContext.getString(R.string.app_loading));
        mLoadingDialog.show();
    }

    public void hideLoadingDialog() {
        if (isFinishing()) return;
        if(mLoadingDialog==null)return;
//        checkDialog(mContext.getString(R.string.app_loading));
        mLoadingDialog.dismiss();
    }

    private void checkDialog(String content) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new QMUITipDialog.Builder(mContext)
                    .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                    .setTipWord(content)
                    .create();
        }else {
            if(mLoadingDialog.isShowing()){
                mLoadingDialog.cancel();
            }
            mLoadingDialog = new QMUITipDialog.Builder(mContext)
                    .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                    .setTipWord(content)
                    .create();
        }
    }

    public void showLoadingDialog(String content) {
        if (isFinishing()) return;
        checkDialog(content);
        mLoadingDialog.show();
    }

    public boolean isNeedSign() {
        return isNeedSign;
    }

    public void setNeedSign(boolean needSign) {
        isNeedSign = needSign;
    }
}
